<template>
  <text class="sub-title"> — 开课设置</text>
  <el-card class="xktime">
    <el-container style="position:fixed;left: 350px;top: 150px">
      <el-text>添加学期:</el-text>
      <el-input v-model="addterm" style="padding-left: 10px; width: 160px" placeholder="eg.22年春" />
    </el-container>
    <el-button type="primary" @click="submit" style="position:fixed;top: 210px;left: 600px;margin-left: 20px">
      提交
    </el-button>
    <el-container style="position: fixed; top: 210px; left: 350px;">
      <el-text >开课学期:</el-text>
      <el-select v-model="sel_cyear" style="width: 180px; margin-left: 10px">
        <el-option
            v-for="year in cyear"
            v-model="sel_cyear"
            :label="year"
            :value="year"
        />
      </el-select>
    </el-container>
    <!-- 添加开课时间选择器 -->
    <el-container style="position: fixed; top: 150px; left: 700px;">
      <el-text style="margin-left: 30px">选课开始时间:</el-text>
      <el-date-picker
          v-model="starttime"
          type="datetime"
          placeholder="选择日期时间"        style="width: 220px; margin-left: 10px"
      />
    </el-container>
    <el-container style="position: fixed; top: 210px; left: 700px;">
      <el-text style="margin-left: 30px">选课结束时间:</el-text>
      <el-date-picker
          v-model="endtime"
          type="datetime"
          placeholder="选择日期时间"        style="width: 220px; margin-left: 10px"
      />
    </el-container>
    <el-button type="primary" @click="submitDateTime" style="position:fixed;top: 210px;left:1070px;">
      提交选课时间
    </el-button>
  </el-card>
  <div class="add-course">
    <title1></title1>
    <Navigation></Navigation>
    <el-row class="cards-container" :gutter="20" justify="space-between">
      <!-- 添加课程信息卡片 -->
      <el-col :xs="24" :sm="24" :md="12">
        <el-card class="box-card">
          <h2>添加课程信息</h2>
          <el-form
            :model="form"
            :rules="rules"
            ref="addCourseForm"
            label-width="120px"
            class="form"
          >
            <el-form-item label="课程号" prop="courseNo">
              <el-input v-model="form.courseNo" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="课程名称" prop="courseName">
              <el-input v-model="form.courseName" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="教师姓名" prop="instructor">
              <el-input v-model="form.instructor" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item label="学分" prop="credits">
              <el-input v-model="form.credits" autocomplete="off" type="number"></el-input>
            </el-form-item>

            <el-form-item label="学期" prop="semester">
              <el-select v-model="form.semester" placeholder="请选择学期">
                <el-option label="春季" value="春季"></el-option>
                <el-option label="秋季" value="秋季"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="描述" prop="description">
              <el-input type="textarea" v-model="form.description"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm" :loading="isSubmitting">提交</el-button>
              <el-button @click="resetForm" :loading="isResetting">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 批量导入课程信息卡片 -->
      <el-col :xs="24" :sm="24" :md="12">
        <el-card class="box-card">
          <h2>批量导入课程信息</h2>
          <el-upload
            class="upload-demo"
            drag
            action=""
            accept=".csv"
            :on-success="handleBatchSuccess"
            :on-error="handleBatchError"
            :before-upload="beforeUpload"
            ref="upload"
            @change="handleFileChange"
            :file-list="fileList"
            :auto-upload="false"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">仅支持CSV文件，大小不超过2MB</div>
          </el-upload>
          <el-button type="primary" @click="submitBatch" :loading="isUploading" style="margin-top: 10px;">导入</el-button>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import Navigation from '@/components/navigation_adm.vue';
import title1 from '@/components/title.vue';


export default {
  name: 'AdmAddCourse',
    components: { Navigation, title1 },
  data() {
    return {
      cyear:[],
      sel_cyear:'',
      starttime: null,
      endtime: null,
      addterm:'',
      form: {
        courseNo: '',
        courseName: '',
        instructor: '',
        credits: '',
        semester: '',
        description: '',
      },
      rules: {
        courseNo: [
          { required: true, message: '请输入课程编号', trigger: 'blur' },
          { pattern: /^\w+$/, message: '课程编号格式错误', trigger: 'blur' },
        ],
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
        ],
        instructor: [
          { required: true, message: '请输入教师姓名', trigger: 'blur' },
        ],
        credits: [
          { required: true, message: '请输入学分', trigger: 'blur' },
          { type: 'number', message: '学分必须为数字', trigger: 'blur' },
          { min: 1, message: '学分至少为1', trigger: 'blur' },
        ],
        semester: [
          { required: true, message: '请选择学期', trigger: 'change' },
        ],
      },
      // 批量导入相关数据
      uploadFile: null,
      fileList: [],
      formData:[],
      isSubmitting: false,
      isResetting: false,
      isUploading: false,
    };
  },
  methods: {
    async submit() {
      try {
        const token = localStorage.getItem('token');
        const userNo = sessionStorage.getItem('UserNo');
        if (!token || !userNo) {
          alert('缺少必要的认证信息，请重新登录。');
          await this.$router.push({name:"Login"})
          return;
        }
        const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/admin/addterm`, null,{
          // method: 'POST',
          headers: {
            token: token,
            // 'Content-Type': 'application/json'
          },
          params:{
            term:this.addterm
          }
        });
        console.log(response.data.code)
        if (response.data.code === '200') {
          ElMessage({
            message: '学期添加成功',
            type: 'success',
          })

        } else {
          alert('提交出错');
        }
      } catch (error) {
        console.error('提交失败', error);
        alert('提交出错，请稍后再试');
      }
    },
    submitForm() {
      this.isSubmitting = true;
      this.$refs.addCourseForm.validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/admin/coursefile`, this.form);
            if (response.data.success) {
              ElMessage.success('课程信息添加成功');
              this.resetForm();
            } else {
              ElMessage.error(response.data.message || '添加失败');
            }
          } catch (error) {
            ElMessage.error('网络错误，请稍后再试');
            console.error(error);
          }
        } else {
          ElMessage.warning('请完善表单信息');
        }
        this.isSubmitting = false;
      });
    },
    resetForm() {
      this.isResetting = true;
      this.$refs.addCourseForm.resetFields();
      this.isResetting = false;
    },


    handleFileChange(file, fileList) {
      console.log('文件变化:', file, fileList); // 调试信息
      const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (isCSV && isLt2M) {
        this.fileList = fileList.slice(-1); // 限制只保留最新选择的一个文件，按需调整
        this.uploadFile = file.raw ; // 存储选中的文件
        console.log('uploadFile 已设置:', this.uploadFile); // 确认uploadFile被赋值
        ElMessage({
            type: 'success',
            message: '上传成功'
          });
      } else {
        this.uploadFile = null;
      }
    },
    beforeUpload(file) {
      const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isCSV) {
        ElMessage.error('只能上传CSV文件!');
      }
      if (!isLt2M) {
        ElMessage.error('文件大小不能超过2MB!');
      }
      return isCSV && isLt2M;
    },
    handleBatchSuccess(response, file, fileList) {
      this.isUploading = false;
      if (response.success) {
        ElMessage.success('批量导入成功');
        this.fileList = [];
      } else {
        ElMessage.error(response.message || '批量导入失败');
      }
    },
    handleBatchError(err, file, fileList) {
      this.isUploading = false;
      ElMessage.error('批量导入失败，请稍后再试');
      console.error(err);
    },
    async submitBatch() {
      if (this.fileList.length === 0) {
        ElMessage.warning('请先选择要导入的CSV文件');
        return;
      }
      console.log(this.uploadFile);
      this.isUploading = true;

      // 构建FormData
      const formData = new FormData();
      formData.append('file', this.uploadFile); // 'file'为后端接收文件的字段名

      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('缺少必要的认证信息，请重新登录。');
          await this.$router.push({ name: 'Login' });
          return;
        }

        const response = await axios.post(
          `${import.meta.env.VITE_API_BASE_URL}/admin/coursefile`, // 确保URL正确

          {
            coursefile: this.uploadFile,
          },
          {
            headers: {
              'Content-Type': 'multipart/form-data', // axios会自动设置boundary
              token: token,
            },
            onUploadProgress: (progressEvent) => {
              const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
              console.log(`上传进度: ${percentCompleted}%`);
              // 可将进度值绑定到data中并在页面上展示
              // this.uploadProgress = percentCompleted;
            },
          }
        );

        console.log('导入响应数据:', response.data); // 调试信息

        if (response.data && response.data.code == 200) { // 确认response.data存在
          ElMessage.success('批量导入成功');
          this.fileList = []; // 清空文件列表
          this.uploadFile = null; // 重置上传文件
          // 执行其他操作，如刷新课程列表
        } else {
          ElMessage.error(response.data.message || '批量导入失败');
        }
      } catch (error) {
        ElMessage.error('批量导入失败，请稍后再试');
        console.error('导入错误:', error);
      } finally {
        this.isUploading = false;
      }
    },
    async loadSemesters() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          alert('缺少必要的认证信息，请重新登录。');
          await this.$router.push({ name: "Login" });
          return;
        }

        const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/public/getTerms`, null,{
          headers: {
            token: token,
          },
        });
        if (response.data.code === '200') {
          this.cyear = response.data.data
          // this.cyear = response.data.data;
          console.log(this.cyear)
        } else {
          ElMessage.error('获取学期信息失败');
        }
      } catch (error) {
        console.error('获取学期信息失败', error);
        ElMessage.error('获取学期信息失败，请稍后再试');
      }
    },

  async submitDateTime() {
    if (!this.starttime||!this.endtime) {
      ElMessage.warning('请选择开课时间');
      return;
    }
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        alert('缺少必要的认证信息，请重新登录。');
        await this.$router.push({ name: "Login" });
        return;
      }
      const fstarttime = this.starttime.toISOString().slice(0, 19);
      const fendtime = this.endtime.toISOString().slice(0, 19);
      console.log(fstarttime)
      console.log(fendtime)
      const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/admin/enablecourse`, null, {
        headers: {
          token: token,
        },
        params:{
          starttime: fstarttime,
          endtime: fendtime,
          term:this.sel_cyear
        }
      });

      if (response.data.code === '200') {
        ElMessage.success('选课时间提交成功');
      } else {
        ElMessage.error('提交选课时间失败');
      }
    } catch (error) {
      console.error('提交选课时间失败', error);
      ElMessage.error('提交选课时间失败，请稍后再试');
    }
  },
  },
  mounted() {
    this.loadSemesters(); // 页面加载时自动获取学期信息
  },
};
</script>

<style scoped>
.add-course {
  padding: 20px;
  width: 80%; /* 确保容器占满全宽 */
  box-sizing: border-box; /* 包括padding在内 */
}

.cards-container {
  /* 使用 Element Plus 的栅格系统，不需要额外的 flex 样式 */
  /* position:fixed; */
    left:150px;
    top:100px;
}

.form {
  max-width: 100%;
  margin: 0 auto;
}

.upload-demo i {
  font-size: 28px;
  color: #1890ff;
}
.upload-demo .el-upload__text {
  margin-top: 10px;
  font-size: 14px;
  color: #bfbfbf;
}
.upload-demo .el-upload__tip {
  font-size: 12px;
  color: #bfbfbf;
}

/* 确保卡片在大屏幕下各占一半 */
@media (min-width: 768px) {
  .cards-container .el-col {
    /* 移除 flex 对齐，保持默认布局 */
    display: block;
    padding: 0;
  }
  
  .cards-container .el-col .box-card {
    width: 100%; /* 让卡片占满列 */
  }
}
.sub-title{
  z-index: 2;
  position: fixed;
  top: 35px;
  left: 380px;
  color: #0e4bbd;
  font-size: 30px;
  font-weight: normal;
}
.addterm{
  position: fixed;
  left: 380px;
  top: 140px;
  font-weight: bold;
  font-size:25px;
}
.xktime{
  position: fixed;
  top: 100px; /* 调整这个值以确保矩形位于 check 类图层下面 */
  left: 20%;
  width: 60%;
  opacity: 0.9;
  height: 200px;
}
</style>